package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.CvProjectInfo;
import cn.com.hhrcw.entity.SysUser;
import cn.com.hhrcw.mapstruct.CvProjectInfoConvert;
import cn.com.hhrcw.params.CommonParams;
import cn.com.hhrcw.params.CvProjectInfoParams;
import cn.com.hhrcw.service.ICvProjectInfoService;
import cn.com.hhrcw.service.ICvTimeDurationCompareService;
import cn.com.hhrcw.utils.SubjectUtils;
import cn.com.hhrcw.vo.CvProjectInfoVO;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.enums.ExperienceTypeEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.function.Function;

/**
 * 简历-项目经历
 *
 * @author jiangdong
 * @since 2020-10-29
 */
@RestController
@Slf4j
@RequestMapping("/personal/v1/cvProjectInfo")
@Api(tags = "简历-项目经历")
@Validated
public class CvProjectInfoController extends JeecgController<CvProjectInfo, ICvProjectInfoService> {

    @Autowired
    private ICvProjectInfoService cvProjectnfoService;

    @Autowired
    private CvProjectInfoConvert cvProjectInfoConvert;

    @Autowired
    private ICvTimeDurationCompareService cvTimeDurationCompareService;


    /**
     * 分页列表查询
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list")
    @AutoLog("简历-项目经历-分页列表查询")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @PermissionData
    public Result<Page<CvProjectInfoVO>> list(CvProjectInfoParams params, HttpServletRequest request) {
        QueryWrapper<CvProjectInfo> queryWrapper = QueryGenerator.initQueryWrapper(cvProjectInfoConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        IPage<CvProjectInfo> page = cvProjectnfoService.page(params.page(), queryWrapper);
        //分页结果转换器
        Function<CvProjectInfo, CvProjectInfoVO> fun = cvProjectInfo -> cvProjectInfoConvert.toVO(cvProjectInfo);

        return Result.ok((Page) page.convert(fun));
    }

    /**
     * 根据id查询
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @PermissionData
    public Result<CvProjectInfoVO> queryById(String id) {
        CvProjectInfo cvProjectInfo = cvProjectnfoService
            .lambdaQuery()
            .eq(CvProjectInfo::getId, id)
            .eq(CvProjectInfo::getDelFlag, false)
            .one();
        if (cvProjectInfo == null) {
            throw new JeecgBootException("数据不存在");
        }
        return Result.ok(cvProjectInfoConvert.toVO(cvProjectInfo));
    }

    /**
     * 项目经历添加
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/add")
    @AutoLog("简历-项目经历-添加")
    @ApiOperation(value = "添加", notes = "添加")
    public Result<?> add(@RequestBody @Valid CvProjectInfoParams params) {

        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        if (!params.getUserId().equals(sysUser.getId())) {
            return Result.error("信息填写错误");
        }
        CvProjectInfo cvProjectInfo = cvProjectInfoConvert.toEntity(params);
        cvProjectInfo.setCreateBy(sysUser.getId());
        cvProjectInfo.setCreateTime(DateUtil.date());
        cvProjectInfo.setDelFlag(false);
        // 判断时间段重复
        /**
         * modified by fangsong 20240403
         * 针对有人同时做几个项目的情况，去掉项目的时间段重复判定
         */
        /*boolean isRepeat = cvTimeDurationCompareService.isTimeDurationRepeat(ExperienceTypeEnum.PROJECT.getValue(),
            sysUser.getId(),cvProjectInfo.getResumeId(),false,null,cvProjectInfo.getStartTime(),cvProjectInfo.getEndTime());
        if(isRepeat) return Result.error("操作失败，请检查开始时间和结束时间");*/

        boolean saved = cvProjectnfoService.save(cvProjectInfo);
        return saved ? Result.ok() : Result.error("添加失败");
    }

    /**
     * 项目经历编辑
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/edit")
    @AutoLog("简历-项目经历-编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    public Result<?> edit(@RequestBody @Valid CvProjectInfoParams params) {
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        if (!params.getUserId().equals(sysUser.getId())) {
            return Result.error("信息填写错误");
        }
        CvProjectInfo cvProjectInfo = cvProjectInfoConvert.toEntity(params);
        cvProjectInfo.setUpdateBy(sysUser.getId());
        cvProjectInfo.setUpdateTime(DateUtil.date());
        // 判断时间段重复
        /**
         * modified by fangsong 20240403
         * 针对有人同时做几个项目的情况，去掉项目的时间段重复判定
         */
        /*boolean isRepeat = cvTimeDurationCompareService.isTimeDurationRepeat(ExperienceTypeEnum.PROJECT.getValue(),
            sysUser.getId(),cvProjectInfo.getResumeId(),true,cvProjectInfo.getId(),cvProjectInfo.getStartTime(),cvProjectInfo.getEndTime());
        if(isRepeat) return Result.error("操作失败，请检查开始时间和结束时间");*/
        boolean updated = cvProjectnfoService.updateById(cvProjectInfo);
        return updated ? Result.ok() : Result.error("编辑失败");
    }

    /**
     * 批量删除
     *
     * @param params 数据id
     * @return
     */
    @PostMapping(value = "/delete")
    @AutoLog("简历-项目经历-批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    public Result delete(@RequestBody CommonParams params) {
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        CvProjectInfo one = cvProjectnfoService.lambdaQuery()
            .eq(CvProjectInfo::getId, params.getId())
            .eq(CvProjectInfo::getUserId, sysUser.getId())
            .eq(CvProjectInfo::getDelFlag, false)
            .one();
        Assert.notNull(one, "删除失败");
        one.setDelFlag(true);
        boolean deleted = cvProjectnfoService.updateById(one);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
     * 属性值是否重复
     *
     * @return
     */
    @Override
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param params
     */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, CvProjectInfoParams params) {
        CvProjectInfo cvProjectInfo = cvProjectInfoConvert.toEntity(params);
        cvProjectInfo.setDelFlag(false);
        QueryWrapper<CvProjectInfo> queryWrapper = QueryGenerator.initQueryWrapper(cvProjectInfo, request.getParameterMap());
        List<CvProjectInfo> data = cvProjectnfoService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("简历-项目经历", "简历-项目经历");
        String url = super.exportXls(exportParams, CvProjectInfoVO.class, cvProjectInfoConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CvProjectInfo.class);
    }

}
